package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
@Slf4j
//@ConfigurationProperties
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 面试题: spring boot项目如何读取自定义配置?
     * 方案一: @Value
     * 方案二: 通过spring中的Environment对象, 读取自定义配置
     * 方案三: 通过实体类 + @ConfigurationProperties
     *        具体的操作:
     *          1.定义一个实体类, 实体类的属性名称需要和自定义配置的配置项的最后一个名称保持一致
     *          2.在十日类上添加@ConfigurationProperties注解, 并制定配置项前缀
     *          3.在启动类上@EnableConfigurationProperties, 指定当前实体类的类型, 此时该实体类就会被纳入spring容器中
     */

//    @Value(value = "${minio.endpointUrl}")
//    private String endpoint;

//    @Autowired
//    private Environment environment;

    @SneakyThrows
    @Override
    public String fileUpload(MultipartFile file) {

    //    log.info(environment.getProperty("minio.endpointUrl"));



        // 创建桶
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        } else {
            System.out.println("Bucket 'glsx' already exists.");
        }

        // 上传文件
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(originalFilename);
        String fullName = fileName + "." + extName;

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())    // 设置桶的名称
                .object(fullName)        // 设置文件名称
                .stream(file.getInputStream() , file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);

        // 拼接上传的图片的访问地址
        String url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fullName;

        // 返回
        return url;
    }
}
